from django.template.defaultfilters import slugify
import re

def template_format(str):
    """
    This is django's slugify but replaces spaces and
    dashes with underscores. Also ensures a name doesn't
    start or end with an underscore.
    """
    str = re.sub('[-\s]+', '_', slugify(str))
    return str.strip('_')
def options(request):
    """
    This adds the "options" variable to the current context. This variable contains
    all of the current options and their values.
    
    Example template usage:
    {{options.options_app.enable.value}}
    {{options.options_app.superuser_override.description}}
    """
    from models import BooleanOption, ChoiceOption, EnableOption, FloatOption, IntOption, TextOption
    result = {}
    for item in BooleanOption.objects.all():
        if not template_format(item.app) in result:
            result[template_format(item.app)] = {}
        result[template_format(item.app)][template_format(item.name)] = item
    for item in ChoiceOption.objects.all():
        if not template_format(item.app) in result:
            result[template_format(item.app)] = {}
        result[template_format(item.app)][template_format(item.name)] = item
    for item in EnableOption.objects.all():
        if not template_format(item.app) in result:
            result[template_format(item.app)] = {}
        result[template_format(item.app)][template_format('enabled')] = item
    for item in FloatOption.objects.all():
        if not template_format(item.app) in result:
            result[template_format(item.app)] = {}
        result[template_format(item.app)][template_format(item.name)] = item
    for item in IntOption.objects.all():
        if not template_format(item.app) in result:
            result[template_format(item.app)] = {}
        result[template_format(item.app)][template_format(item.name)] = item
    for item in TextOption.objects.all():
        if not template_format(item.app) in result:
            result[template_format(item.app)] = {}
        result[template_format(item.app)][template_format(item.name)] = item
    return {'options':result}